/*
	   _           _      _           _     _ 
	  (_)         | |    | |         (_)   | |
	   _ _   _ ___| |_ __| |_ __ ___  _  __| |
	  | | | | / __| __/ _` | '__/ _ \| |/ _` |
	  | | |_| \__ \ || (_| | | | (_) | | (_| |
	  | |\__,_|___/\__\__,_|_|  \___/|_|\__,_|
	 _/ |                                     
	|__/ 
	
	Copyright 2013 Caspar Isemer and and Eva Krueger, http://justdroid.org
	
	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at
	
		http://www.apache.org/licenses/LICENSE-2.0
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License. 
*/

package org.justdroid.justdroid;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SettingsColor extends JustDroidActivity {
	
	/** Declare variables and UI elements **/
	private Spinner spinnerFg, spinnerBg;
	private SpinnerAdapter adapter;
	private TextView txtForeground, txtBackground, txtPreview;
	private Button btnReset;
	private Editor editor;
	private SharedPreferences preferences;
	private static int flag = 0;
	private int currentSelectionFg = -1, currentSelectionBg = -1;
	
	void attachKeyListener(final Button button) {
		button.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
				if(keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
					switch(keyCode) {
					case KeyEvent.KEYCODE_DPAD_CENTER:
					case KeyEvent.KEYCODE_ENTER:
							reset();
							break;
					}
				}
				return false;
			}
		});
	}
	
	/** Function to attach onTouchListener and onFocusListener to the text views **/
	void attachListenerToTextView(TextView textView) {
		/*textView.setOnTouchListener(new OnTouchListener() {	
			@Override
			public boolean onTouch(View view, MotionEvent arg1) {
				giveFeedback(((TextView)view).getText().toString());
				return false;
			}
		});*/
		
		textView.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View view, boolean hasFocus) {
				if(hasFocus) {
					giveFeedback(((TextView)view).getText().toString());
				}
			}
		});
	}
	
	void reset() {
		SettingsColor.this.preferences = getSharedPreferences(getResources().getString(R.string.color), 0);
		editor = SettingsColor.this.preferences.edit();
		editor.clear();
		editor.commit();
		if(Utils.isAccessibilityEnabled(getApplicationContext()))
			TTS.speak(getResources().getString(R.string.resetColorsSuccess));
		Toast.makeText(getApplicationContext(), getResources().getString(R.string.resetColorsSuccess), Toast.LENGTH_SHORT).show();
	}
	
	/** Function to attach onTouchListener to the spinners **/
	/*void attachListenerToSpinner(Spinner spinner) {
		spinner.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View view, MotionEvent arg1) {
				//vibrate
				Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			    vibrator.vibrate(500);
				return false;
			}
		});
	}*/
	
	/** Function to attach onItemSelectedListener to the spinners **/
	void attachListenerToSpinnerItem(final Spinner spinner) {
		
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@SuppressLint("DefaultLocale")
			@Override
			public void onItemSelected(AdapterView<?> arg0, View view, int position,
					long arg3) {
				if(flag > 1) {
					String color = getResources().getStringArray(R.array.colors)[position];
					int resId = getResources().getIdentifier(color.toLowerCase(), "color", SettingsColor.this.getPackageName());
					
					switch(spinner.getId()) {
					case R.id.fcolors:
						//save in SharedPreferences
						preferences = getSharedPreferences(getResources().getString(R.string.color), 0);
						editor = preferences.edit();
						editor.putInt("fgcolor", resId);
						txtPreview.setTextColor(getResources().getColor(resId));
						if(editor.commit()) {
							if(Utils.isAccessibilityEnabled(getApplicationContext()))
								TTS.speak(spinner.getSelectedItem().toString() + " " + getResources().getString(R.string.appliedColorsSuccess));
							Toast.makeText(getApplicationContext(), spinner.getSelectedItem().toString() + " " + getResources().getString(R.string.appliedColorsSuccess), Toast.LENGTH_SHORT).show();
						}
						else {
							if(Utils.isAccessibilityEnabled(getApplicationContext()))
								TTS.speak(spinner.getSelectedItem().toString() + " " + getResources().getString(R.string.appliedColorsFailure));
							Toast.makeText(getApplicationContext(), spinner.getSelectedItem().toString() + " " + getResources().getString(R.string.appliedColorsFailure), Toast.LENGTH_SHORT).show();
						}
						break;
					case R.id.bcolors:
						//save in SharedPreferences
						preferences = getSharedPreferences(getResources().getString(R.string.color), 0);
						editor = preferences.edit();
						editor.putInt("bgcolor", resId);
						txtPreview.setBackgroundColor(getResources().getColor(resId));
						if(editor.commit()) {
							if(Utils.isAccessibilityEnabled(getApplicationContext()))
								TTS.speak(spinner.getSelectedItem().toString() + " " + getResources().getString(R.string.appliedColorsSuccess));
							Toast.makeText(getApplicationContext(), spinner.getSelectedItem().toString() + " " + getResources().getString(R.string.appliedColorsSuccess), Toast.LENGTH_SHORT).show();
						}
						else {
							if(Utils.isAccessibilityEnabled(getApplicationContext()))
								TTS.speak(spinner.getSelectedItem().toString() + " " + getResources().getString(R.string.appliedColorsFailure));
							Toast.makeText(getApplicationContext(), spinner.getSelectedItem().toString() + " " + getResources().getString(R.string.appliedColorsFailure), Toast.LENGTH_SHORT).show();
						}
						break;
					}
				}
				else {
					flag++;
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}
	
	int getColorIndex(int colorValue) {
		switch(colorValue) {		
		case R.color.cyan:
		default:
			return 0;
		case R.color.black:
			return 1;
		case R.color.blue:
			return 2;
		case R.color.magenta:
			return 3;
		case R.color.grey:
			return 4;
		case R.color.green:
			return 5;
		case R.color.red:
			return 6;
		case R.color.white:
			return 7;
		case R.color.yellow:
			return 8;
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		SettingsColor.flag = 0;
		
		LinearLayout layout = (LinearLayout) findViewById(R.id.settingscolor);
		Utils.applyFontColorChanges(getApplicationContext(), layout);
		Utils.applyFontSizeChanges(getApplicationContext(), layout);
		Utils.applyFontTypeChanges(getApplicationContext(), layout);
		
		int fgColorValue = getSharedPreferences(getResources().getString(R.string.color), 0).getInt("fgcolor", 0);
		int bgColorValue = getSharedPreferences(getResources().getString(R.string.color), 0).getInt("bgcolor", 0);
		
		spinnerBg.setSelection(getColorIndex(bgColorValue));
		spinnerFg.setSelection(getColorIndex(fgColorValue));
	}

	/** Create the Contact Details menu activity **/
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.settingscolor);
		super.onCreate(savedInstanceState);
		/** get UI elements **/
		spinnerFg = (Spinner) findViewById(R.id.fcolors);
		spinnerBg = (Spinner) findViewById(R.id.bcolors);
		txtPreview = (TextView) findViewById(R.id.txtPreview);
		txtForeground = (TextView) findViewById(R.id.txtForeground);
		txtBackground = (TextView) findViewById(R.id.txtBackground);
		btnReset = (Button) findViewById(R.id.btnApplyColors);
		
		adapter = new SpinnerAdapter(getApplicationContext(), Utils.colorNames);
		spinnerFg.setAdapter(adapter);
		spinnerBg.setAdapter(adapter);
		
		attachListenerToTextView(txtForeground);
		attachListenerToTextView(txtBackground);
		
		//attachListenerToSpinner(spinnerFg);
		//attachListenerToSpinner(spinnerBg);
		
		attachListenerToSpinnerItem(spinnerFg);
		attachListenerToSpinnerItem(spinnerBg);
		
		attachListener(btnReset);
		
		attachKeyListener(btnReset);
		
		btnReset.setOnClickListener(new OnClickListener() {	
			@Override
			public void onClick(View view) {
				reset();
			}
		});
		
		spinnerFg.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
				Spinner spinner = (Spinner) view;
				if(keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
					switch(keyCode) {
					case KeyEvent.KEYCODE_DPAD_DOWN:
						currentSelectionFg++;
						if(currentSelectionFg == spinner.getCount()) {
							currentSelectionFg = 0;
						}
						giveFeedback(spinnerFg.getItemAtPosition(currentSelectionFg).toString());
						spinner.setSelection(currentSelectionFg);
						break;
					}
				}
				return false;
			}
		});
		
		spinnerBg.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
				Spinner spinner = (Spinner) view;
				if(keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
					switch(keyCode) {
					case KeyEvent.KEYCODE_DPAD_DOWN:
						currentSelectionBg++;
						if(currentSelectionBg == spinner.getCount()) {
							currentSelectionBg = 0;
						}
						giveFeedback(spinnerBg.getItemAtPosition(currentSelectionBg).toString());
						spinner.setSelection(currentSelectionBg);
						break;
					}
				}
				return false;
			}
		});
		/** Put most everything before here **/
	}
}
